package com.cloudansys.core.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SerializeUtil {

    private static final ObjectMapper objectMapper = getObjectMapper();

    /**
     * 序列化
     */
    public static byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        try {
            return objectMapper.writeValueAsBytes(object);
        } catch (Exception ex) {
            log.error("序列化失败！");
            return null;
        }
    }

    /**
     * 反序列化
     */
    public static Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length==0) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, 0, bytes.length, Object.class);
        } catch (Exception ex) {
            log.error("反序列化失败！");
            return null;
        }
    }

    /**
     * @return ObjectMapper
     */
    public static ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会抛出异常
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return objectMapper;
    }

}
